package mcia_gui;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;

/*
 * AdmWlcome.java - It is frame that appears when user with 'administrator' priviliges log in.
 * It displays possible acition for user - import project, manage account, view global or local scenes.
 *
 * @author MCIA
 */
public class AdmWelcome extends javax.swing.JFrame {

    private DatabaseEss db;                                                     //connection to db
    private String dbName = "mcia";                                             //name of db we are connecting to
    private String currentFloorDescription = null;                              //show floor description
    private int currentFloor = 1;                                               //used to forward selected floor
    private int currentCL = 0;                                                  //used to forward selected cl
    private int loadedAll = 0;                                                  //lock for comboboxes

    public AdmWelcome() {
        initComponents();

        descriptionLabel.setText("");

        //setting text in status label
        statusLabel.setText("User: " + LogOn.globalUsername);

        db = new DatabaseEss(dbName);
        //reading floors and cls
        readFloorsFromDB(1);

        if (floorCombo.getItemCount() > 0) {
            currentFloorDescription = floorCombo.getSelectedItem().toString();
            System.out.println(currentFloorDescription);
        }

        loadedAll = 1;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jPanel1 = new javax.swing.JPanel();
        statusLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        mainTitleLabel = new javax.swing.JLabel();
        descriptionLabel = new javax.swing.JLabel();
        editLSButton = new javax.swing.JButton();
        editGSButton = new javax.swing.JButton();
        importProjectButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        floorCombo = new javax.swing.JComboBox();
        clCombo = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        viewButton = new javax.swing.JToggleButton();
        logoutButton = new javax.swing.JButton();
        accountsButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MCIA LightControl");
        setBounds(new java.awt.Rectangle(200, 20, 800, 600));
        setMaximizedBounds(new java.awt.Rectangle(0, 0, 800, 600));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setResizable(false);

        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        statusLabel.setText("User: Admin");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)
        );

        jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        mainTitleLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        mainTitleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        mainTitleLabel.setText("Choose the View");

        descriptionLabel.setForeground(new java.awt.Color(51, 102, 255));
        descriptionLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        descriptionLabel.setText("Description Label");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(descriptionLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE)
                    .addComponent(mainTitleLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 774, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(mainTitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(descriptionLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        editLSButton.setText("Edit Local Scenes");
        editLSButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editLSButtonActionPerformed(evt);
            }
        });

        editGSButton.setText("Edit Global Scenes");
        editGSButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editGSButtonActionPerformed(evt);
            }
        });

        importProjectButton.setText("Import Project File ...");
        importProjectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                importProjectButtonActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Select area to view", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel4.setText("Choose Floor:");

        floorCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- no items -" }));
        floorCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                floorComboActionPerformed(evt);
            }
        });

        clCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "- no items -" }));
        clCombo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clComboActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel6.setText("Choose CL:");

        viewButton.setFont(new java.awt.Font("Tahoma", 0, 14));
        viewButton.setText("View");
        viewButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(90, 90, 90)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(clCombo, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(floorCombo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(viewButton, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(98, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(floorCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(clCombo, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addComponent(viewButton, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(55, Short.MAX_VALUE))
        );

        logoutButton.setText("Logout");
        logoutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                logoutButtonActionPerformed(evt);
            }
        });

        accountsButton.setText("Manage Accounts");
        accountsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                accountsButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(84, 84, 84)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(85, Short.MAX_VALUE))
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addComponent(editLSButton, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(editGSButton, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(77, 77, 77)
                .addComponent(importProjectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 75, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(accountsButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(logoutButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE))
                .addGap(21, 21, 21))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(71, 71, 71)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(113, 113, 113)
                .addComponent(accountsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(logoutButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(editLSButton, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                        .addComponent(editGSButton, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE)
                        .addComponent(importProjectButton, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE)))
                .addGap(17, 17, 17)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void importProjectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importProjectButtonActionPerformed
        AdmAddFile aafilescreen = new AdmAddFile();
        Main.changeFrame(aafilescreen);
    }//GEN-LAST:event_importProjectButtonActionPerformed

    private void viewButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewButtonActionPerformed
        AdmLSView admLocalScreen = new AdmLSView(currentFloor, currentFloorDescription, currentCL);
        Main.changeFrame(admLocalScreen);
    }//GEN-LAST:event_viewButtonActionPerformed

    private void editLSButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editLSButtonActionPerformed
        AdmLSView admLocalScreen = new AdmLSView();
        Main.changeFrame(admLocalScreen);
    }//GEN-LAST:event_editLSButtonActionPerformed

    private void editGSButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editGSButtonActionPerformed
        AdmGSChooser AdmGlobScreen = new AdmGSChooser();
        AdmGlobScreen.setVisible(true);
    }//GEN-LAST:event_editGSButtonActionPerformed

    private void logoutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_afdsActionPerformed
        LogOn firstScreen = new LogOn();
        Main.changeFrame(firstScreen);
    }//GEN-LAST:event_afdsActionPerformed

    private void accountsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accountsButtonActionPerformed
        AdmManageAccounts manageAcc = new AdmManageAccounts();
        Main.changeFrame(manageAcc);
    }//GEN-LAST:event_accountsButtonActionPerformed

    private void floorComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_floorComboActionPerformed
        //filtering CLs for particular floor
        if (loadedAll == 1) {
            currentFloorDescription = floorCombo.getSelectedItem().toString();

            //getting floor id
            int floorID = 1;
            try {
                db.stmt = db.conn.createStatement();
                ResultSet results;
                String query;
                query = "SELECT floor FROM units WHERE description = '" + currentFloorDescription + "'";
                results = db.stmt.executeQuery(query);

                results.next();
                floorID = results.getInt("FLOOR");

                results.close();

                //closing connection
                db.stmt.close();

            } catch (SQLException ex) {
                Logger.getLogger(ManagerLSView.class.getName()).log(Level.SEVERE, null, ex);
            }

            currentFloor = floorID;
            readFloorsFromDB(currentFloor);

            floorCombo.setSelectedItem(currentFloorDescription);
            clCombo.setSelectedIndex(0);
        }
    }//GEN-LAST:event_floorComboActionPerformed

    private void clComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clComboActionPerformed
        //getting id of selected CL
        currentCL = clCombo.getSelectedIndex();
    }//GEN-LAST:event_clComboActionPerformed

    private int readFloorsFromDB(int currentFloor) {
        //reading floors from database
        try {
            floorCombo.removeAllItems();
            clCombo.removeAllItems();

            clCombo.addItem("- Whole Floor -");

            //loading floors into combo
            db.stmt = db.conn.createStatement();
            ResultSet results0 = db.stmt.executeQuery("SELECT * FROM units");
            while (results0.next()) {
                if (results0.getString("CL").equals("0") && results0.getString("LIGHT").equals("0")) {
                    //adding floor to comboList in right position (sort)
                    String floorName = results0.getString("DESCRIPTION");
                    int howMany = floorCombo.getItemCount();
                    boolean added = false;
                    for (int i = 0; i < howMany; i++) {
                        String obj = floorCombo.getItemAt(i).toString();
                        String stringToCompare = floorName;
                        String stringToCompare2 = obj;
                        int compare = stringToCompare.compareToIgnoreCase(stringToCompare2);
                        int numberLength1 = stringToCompare.indexOf(".");
                        int numberLength2 = stringToCompare2.indexOf(".");
                        if (numberLength1 < numberLength2) {
                            floorCombo.insertItemAt(floorName, i);
                            added = true;
                            break;
                        } else if (compare <= 0 && numberLength1 == numberLength2) {
                            floorCombo.insertItemAt(floorName, i);
                            added = true;
                            break;
                        }
                    }
                    if (added == false) {
                        floorCombo.addItem(floorName);
                    }
                }
                if (results0.getString("FLOOR").equals("" + currentFloor) && !results0.getString("CL").equals("0") && results0.getString("LIGHT").equals("0")) {
                    clCombo.addItem("CL " + results0.getString("FLOOR") + "." + results0.getString("CL"));
                }
            }
            results0.close();

            if (floorCombo.getItemCount() == 0) {
                descriptionLabel.setText("No project is imported! Ask Administrator to import a project first!");
                System.out.println("WARNING: No project imported!");

                viewButton.setEnabled(false);
                editLSButton.setEnabled(false);
                editGSButton.setEnabled(false);
                floorCombo.setEnabled(false);
                clCombo.setEnabled(false);

                return -1;
            }

        } catch (SQLException ex) {
            Logger.getLogger(ManagerWelcome.class.getName()).log(Level.SEVERE, null, ex);
        }
        return 0;
    }

    public static void main(String args[]) {

        //setting Windows Look and Feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            System.out.println("Error setting native LAF: " + ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    LogOn thisFrame = new LogOn();
                    String[] vars = null;
                    Main.main(vars);
                    Main.changeFrame(thisFrame);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(AdmWelcome.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InstantiationException ex) {
                    Logger.getLogger(AdmWelcome.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton accountsButton;
    private javax.swing.JComboBox clCombo;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JButton editGSButton;
    private javax.swing.JButton editLSButton;
    private javax.swing.JComboBox floorCombo;
    private javax.swing.JButton importProjectButton;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JButton logoutButton;
    private javax.swing.JLabel mainTitleLabel;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JToggleButton viewButton;
    // End of variables declaration//GEN-END:variables
}
